package cn.caplike.demo.spring.security.jwt.controller;

import cn.caplike.demo.spring.security.jwt.domain.entity.User;
import cn.caplike.demo.spring.security.jwt.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * Auth Controller
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-04-22 11:14
 */
@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {

    private UserMapper userMapper;

    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * Description: 注册
     *
     * @param registerUser 用户信息
     * @return java.lang.String
     * @author LiKe
     * @date 2020-04-24 09:22:54
     * @see cn.caplike.demo.spring.security.jwt.filter.JWTAuthenticationFilter
     * @see cn.caplike.demo.spring.security.jwt.filter.JWTAuthorizationFilter
     */
    @PostMapping("/register")
    public User registerUser(@RequestBody Map<String, String> registerUser) {
        User user = new User();
        user.setName(registerUser.get("name"));
        // 记得注册的时候把密码加密一下
        user.setPassword(bCryptPasswordEncoder.encode(registerUser.get("password")));
        user.setRole("USER");
        log.debug("AuthController: {}", userMapper.save(user));
        return user;
    }

    @Autowired
    public void setBCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
}
